package com.yupi.springbootinit.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.TimeoutException;

/**
 * @version 1.0
 * @Author moresuo
 * @Date 2024/3/6 20:45
 * @注释
 */
public class TopicProducer {
    private static final String EXCHANGE_NAME = "topic_exchange";

    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接工厂对象
        ConnectionFactory factory=new ConnectionFactory();
        //设置消息队列主机信息
        factory.setHost("111.229.199.44");
        factory.setUsername("admin");
        factory.setPassword("admin");
        factory.setPort(5672);
        try (Connection connection=factory.newConnection();
             Channel channel=connection.createChannel()){
            //声明交换机和类型
            channel.exchangeDeclare(EXCHANGE_NAME, "topic");
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()) {
                String userInput=scanner.nextLine();
                String[] strings = userInput.split(" ");
                if(strings.length<1){
                    continue;
                }
                String message = strings[0];
                String routingKey = strings[1];
                channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes("UTF-8"));
                System.out.println(" [x] Sent '" + message + "' with routing: '" + routingKey + "'");
            }
        }
    }
}
